package xxxx.com.controller.login;

import xxxx.com.constant.Const;
import xxxx.com.controller.BaseServlet;
import xxxx.com.model.User;
import xxxx.com.service.UserService;
import xxxx.com.service.impl.UserServiceImpl;
import xxxx.com.utils.MailUtil;
import xxxx.com.utils.StrUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;


@WebServlet("/login/*")
public class LoginServlet extends BaseServlet {

    private static UserService userService = new UserServiceImpl();

    // 登录
    public void toLogin(HttpServletRequest req, HttpServletResponse resp) {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String remember = req.getParameter("remember");
        User user = userService.findUserByName(username);
        try {
            // 判断数据库是否存在与username匹配数据
            if (null != user) {
                // 判断user的密码和前端输入的密码是否匹配
                if (user.getPassword().equals(password)) {
                    // 判断是否点击记住我
                    if (StrUtil.checkString(remember)) {
                        // 创建保存用户信息的Cookie，存于客户端
                        Cookie cookie = new Cookie("userInfo", username);
                        // 设置Cookie的最大存活时间（7天）
                        cookie.setMaxAge(Const.MAX_COOKIE_TIME);
                        // 设置Cookie的使用路径，在全局使用
                        cookie.setPath("/");
                        resp.addCookie(cookie);
                    }

                    // 更新用户登陆时间
                    userService.updateLoginTime(user.getId());
                    // 登录成功后，设置会话域保存用户ID，方便过滤器做登录拦截
                    // 以及后面页面渲染的时候，获取用户基本信息时，可以拿出用户ID去写sql查询基本数据
                    req.getSession().setAttribute("userId", user.getId());
                    Map<String, Object> userMap = userService.findUserById(user.getId());
                    req.getSession().setAttribute("userBaseInfo", userMap);
//                    System.out.println(userMap);
                    resp.sendRedirect(req.getContextPath() + "/view/gohome");
                    return;
                }

            }
            req.getSession().setAttribute("logmsg", "用户名或密码错误");
            resp.sendRedirect(req.getContextPath() + "/view/reindex");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    // 退出登录并且清除Cookie
    public void toLoginOut(HttpServletRequest req, HttpServletResponse resp) {
        Cookie[] cookies = req.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                if ("userInfo".equals(cookie.getName())) {
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    resp.addCookie(cookie);
                    break;
                }
            }
        }
        try {
            resp.sendRedirect(req.getContextPath() + "/");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    // 注册
    public void toRegister(HttpServletRequest req, HttpServletResponse resp) {
        String email = req.getParameter("email");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String password2 = req.getParameter("password2");
        try {
            if (StrUtil.checkString(email) && StrUtil.checkEmail(email)) {
                if (StrUtil.checkString(username) && StrUtil.checkString(password)) {
                    if (password.equals(password2)) {
                        // 通过用户名查找数据库信息
                        User user = userService.findUserByName(username);
                        if (null != user) {
                            req.getSession().setAttribute("regmsg", "该用户名已存在");
                            resp.sendRedirect(req.getContextPath() + "/view/register");
                        } else {
                            User userByEmail = userService.findUserByEmail(email);
                            if (null != userByEmail) {
                                req.getSession().setAttribute("regmsg", "该邮箱已注册");
                                resp.sendRedirect(req.getContextPath() + "/view/register");
                            } else {
                                // 通过检测，可以添加进入数据库
                                userService.addUser(username, password, email);
                                resp.sendRedirect(req.getContextPath() + "/view/index");
                            }
                        }
                    } else {
                        req.getSession().setAttribute("regmsg", "密码不一致，请重新输入");
                        resp.sendRedirect(req.getContextPath() + "/view/register");
                    }
                } else {
                    req.getSession().setAttribute("regmsg", "用户名或密码不能为空");
                    resp.sendRedirect(req.getContextPath() + "/view/register");
                }
            } else {
                req.getSession().setAttribute("regmsg", "邮箱输入有误");
                resp.sendRedirect(req.getContextPath() + "/view/register");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // 发送邮箱验证码
    public void sendCode(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String email = req.getParameter("email");
            HttpSession session = req.getSession();
            if (StrUtil.checkString(email) && StrUtil.checkEmail(email)) {
                // 判断session中有没有验证码
                Object obj = session.getAttribute(email);
                //System.out.println("sendCode的email：" + obj);
                if (null == obj) {
                    // 没有则发送验证到用户邮箱
                    try {
                        String title = "“Xiao Biao Jiao You” reset password";
                        String code = StrUtil.randomCode();
//                        System.out.println("sendCode的code：" + code);
                        String content = "Your verification code is :" + code;
                        session.setAttribute(email, code);
                        session.setMaxInactiveInterval(Const.MAX_CODE_TIME);
                        MailUtil.send(email, title, content, MailUtil.UNICODE);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    resp.getWriter().write("验证码发送成功，请查收");
                } else {
                    resp.getWriter().write("验证码已发送到您的邮箱，请查收");
                }
            } else {
                resp.getWriter().write("邮箱格式有误，请重新输入");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // 通过验证码，修改用户密码
    public void resetPwd(HttpServletRequest req, HttpServletResponse resp) {
        String email = null;
        try {
            email = req.getParameter("email");
            String checkCode = req.getParameter("checkCode");
            String password = req.getParameter("password");
            HttpSession session = req.getSession();
//            System.out.println("resetPwd的email：" + email);
//            System.out.println("resetPwd的checkCode：" + checkCode);
//            System.out.println("resetPwd的password：" + password);
            // 判断邮箱非空&&判断邮箱格式无误
            if (StrUtil.checkString(email) && StrUtil.checkEmail(email)) {
                Object emails = session.getAttribute(email);
//                System.out.println("resetPwd的session中email的值：" + emails);
                if (null != emails) {
                    String emailCode = emails.toString();
                    if (emailCode.equals(checkCode) && StrUtil.checkString(password)) {
                        // 重置密码
                        User userByEmail = userService.findUserByEmail(email);
                        if (null != userByEmail) {
                            userService.resetPwd(userByEmail.getId(), password);
                            req.getSession().removeAttribute(email);
                            resp.sendRedirect(req.getContextPath() + "/view/index");
                            return;
                        }
                    }
                }
            }
            req.getSession().setAttribute("forgetmsg", "重置密码失败");
            resp.sendRedirect(req.getContextPath() + "/view/forget");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}